package igou.togogo.controller;

import igou.togogo.domain.ProductDetail;
import igou.togogo.domain.ProductResult;
import igou.togogo.page.Pagination;
import igou.togogo.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    IProductService productService;

    @RequestMapping("/list")
    public String getProductByBrandId(Integer brandId,
                                      Integer page,
                                      Integer rows,
                                      Model model, HttpServletRequest request) {
        ProductResult result = productService.getProductByBrandId(brandId, page, rows);
        List<ProductDetail> productList = result.getList();
        Pagination pagination = result.getPagination();
        String url = "/product/list.action";
        StringBuilder params = new StringBuilder("brandId=" + brandId.toString());
        params.append("&rows=" + rows);
        pagination.pageView(url, params.toString());
        model.addAttribute("brandId", brandId);
        model.addAttribute("productList", productList);
        model.addAttribute("pagination", pagination);
        model.addAttribute("brandList", request.getSession().getAttribute("brandList"));
        return "front_page/product/product";
    }

    @RequestMapping("/detail/{id}")
    public String getProductDetail(@PathVariable("id") Integer id,
                                   @RequestParam(value = "color_id", required = false, defaultValue = "") String colorId,
                                   Model model) {
        ProductDetail productDetail = productService.getProductDetail(id, colorId);
        model.addAttribute("product", productDetail);
        return "front_page/product/productDetail";
    }

}
